using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using SupplierCustomerManagement.Infrastructure;
using SupplierCustomerManagement.Domain.ReportForms;

namespace SupplierCustomerManagement.Read.API.Data
{
    public static class DataSeeder
    {
        public static async Task SeedAsync(IServiceProvider services, CancellationToken cancellationToken = default)
        {
            using var scope = services.CreateScope();
            var db = scope.ServiceProvider.GetRequiredService<SupplierDbContext>();

            // 确保数据库存在（如使用迁移，可替换为 db.Database.MigrateAsync()）
            await db.Database.EnsureCreatedAsync(cancellationToken);
            // 不再直接返回：采用“补齐”策略，确保关键表至少有100条数据。

            var rand = new Random(1234);
            var farmId = 1;
            var breeds = new[] { "杜泊", "澳洲白", "萨福克" };

            // 1) 种母与种公
            var ewes = new List<Sheep>();
            var rams = new List<Sheep>();
            for (int i = 0; i < 50; i++)
            {
                ewes.Add(new Sheep
                {
                    EarTag = $"E-{1000 + i}",
                    SheepName = $"母羊{i}",
                    Breed = breeds[rand.Next(breeds.Length)],
                    Gender = "母",
                    BirthDate = DateTime.Today.AddMonths(-rand.Next(12, 72)),
                    Age = rand.Next(12, 72),
                    SheepType = "种母",
                    CurrentStatus = rand.NextDouble() < 0.6 ? "怀孕" : (rand.NextDouble() < 0.5 ? "空怀" : "待配"),
                    HealthStatus = "健康",
                    CurrentLocation = "A圈",
                    FarmId = farmId
                });
            }
            for (int i = 0; i < 10; i++)
            {
                rams.Add(new Sheep
                {
                    EarTag = $"R-{2000 + i}",
                    SheepName = $"公羊{i}",
                    Breed = breeds[rand.Next(breeds.Length)],
                    Gender = "公",
                    BirthDate = DateTime.Today.AddMonths(-rand.Next(12, 72)),
                    Age = rand.Next(12, 72),
                    SheepType = "种公",
                    CurrentStatus = "存栏",
                    HealthStatus = "健康",
                    CurrentLocation = "B圈",
                    FarmId = farmId
                });
            }
            db.Sheeps.AddRange(ewes);
            db.Sheeps.AddRange(rams);
            await db.SaveChangesAsync(cancellationToken);

            // 建立 EarTag->Id 映射（如果需要），这里直接用索引随机选
            var eweIds = ewes.Select(e => e.Id).ToList();
            var ramIds = rams.Select(r => r.Id).ToList();

            // 2) 配种记录（近一年分布到每个月）
            var today = DateTime.Today;
            var yearStart = new DateTime(today.Year, 1, 1);
            var breedingRecords = new List<BreedingRecord>();
            for (int m = 1; m <= 12; m++)
            {
                var monthDate = new DateTime(today.Year, m, 1);
                int count = rand.Next(5, 15);
                for (int j = 0; j < count; j++)
                {
                    var eweId = eweIds[rand.Next(eweIds.Count)];
                    var ramId = ramIds[rand.Next(ramIds.Count)];
                    var breedingDate = monthDate.AddDays(rand.Next(0, 28));
                    var expectedLambing = breedingDate.AddDays(150 + rand.Next(-5, 6)); // 约5个月

                    breedingRecords.Add(new BreedingRecord
                    {
                        EweId = eweId,
                        RamId = ramId,
                        BreedingDate = breedingDate,
                        BreedingType = "自然",
                        BreedingMethod = "群配",
                        ExpectedLambingDate = expectedLambing,
                        IsSuccessful = rand.NextDouble() < 0.7,
                        FarmId = farmId
                    });
                }
            }
            db.BreedingRecords.AddRange(breedingRecords);
            await db.SaveChangesAsync(cancellationToken);

            var breedingIds = breedingRecords.Select(b => b.Id).ToList();

            // 3) 妊检记录（部分阳性）
            var pregChecks = new List<PregnancyCheck>();
            foreach (var b in breedingRecords)
            {
                if (rand.NextDouble() < 0.65)
                {
                    pregChecks.Add(new PregnancyCheck
                    {
                        BreedingId = b.Id,
                        CheckDate = b.BreedingDate.AddDays(35 + rand.Next(-3, 4)),
                        CheckMethod = "B超",
                        CheckResult = rand.NextDouble() < 0.85 ? "怀孕" : "未孕",
                        GestationWeek = 5,
                        Notes = null
                    });
                }
            }
            db.PregnancyChecks.AddRange(pregChecks);
            await db.SaveChangesAsync(cancellationToken);

            // 4) 分娩记录（依据部分预计分娩日期落入 now±30 天窗口，生成1-2胎）
            var lambingRecords = new List<LambingRecord>();
            foreach (var b in breedingRecords.Where(x => x.ExpectedLambingDate.HasValue))
            {
                if (rand.NextDouble() < 0.55)
                {
                    var date = b.ExpectedLambingDate!.Value.AddDays(rand.Next(-7, 8));
                    var total = 1 + (rand.NextDouble() < 0.3 ? 1 : 0);
                    lambingRecords.Add(new LambingRecord
                    {
                        EweId = b.EweId,
                        LambingDate = date,
                        TotalLambs = total,
                        LiveLambs = total,
                        DeadLambs = 0,
                        LambingType = "顺产",
                        LambingStatus = "正常",
                        FarmId = farmId
                    });
                }
            }
            db.LambingRecords.AddRange(lambingRecords);
            await db.SaveChangesAsync(cancellationToken);

            // ================= 追加：补齐至至少100条 =================
            // 1) Sheep
            var sheepCount = await db.Sheeps.AsNoTracking().CountAsync(cancellationToken);
            if (sheepCount < 100)
            {
                var add = 100 - sheepCount;
                var list = new List<Sheep>();
                for (int i = 0; i < add; i++)
                {
                    var isEwe = rand.NextDouble() < 0.8;
                    list.Add(new Sheep
                    {
                        EarTag = (isEwe ? "E-" : "R-") + (3000 + sheepCount + i),
                        SheepName = (isEwe ? "母羊" : "公羊") + (sheepCount + i),
                        Breed = breeds[rand.Next(breeds.Length)],
                        Gender = isEwe ? "母" : "公",
                        BirthDate = DateTime.Today.AddMonths(-rand.Next(12, 72)),
                        Age = rand.Next(12, 72),
                        SheepType = isEwe ? "种母" : "种公",
                        CurrentStatus = isEwe ? (rand.NextDouble() < 0.6 ? "怀孕" : (rand.NextDouble() < 0.5 ? "空怀" : "待配")) : "存栏",
                        HealthStatus = "健康",
                        CurrentLocation = isEwe ? "A圈" : "B圈",
                        FarmId = farmId
                    });
                }
                db.Sheeps.AddRange(list);
                await db.SaveChangesAsync(cancellationToken);
            }

            eweIds = await db.Sheeps.AsNoTracking().Where(s => s.Gender == "母").Select(s => s.Id).ToListAsync(cancellationToken);
            ramIds = await db.Sheeps.AsNoTracking().Where(s => s.Gender == "公").Select(s => s.Id).ToListAsync(cancellationToken);

            // 2) BreedingRecord
            var brCount = await db.BreedingRecords.AsNoTracking().CountAsync(cancellationToken);
            if (brCount < 100 && eweIds.Any() && ramIds.Any())
            {
                var add = 100 - brCount;
                var list = new List<BreedingRecord>();
                for (int i = 0; i < add; i++)
                {
                    var d = DateTime.Today.AddDays(-rand.Next(0, 365));
                    list.Add(new BreedingRecord
                    {
                        EweId = eweIds[rand.Next(eweIds.Count)],
                        RamId = ramIds[rand.Next(ramIds.Count)],
                        BreedingDate = d,
                        BreedingType = rand.NextDouble() < 0.2 ? "人工" : "自然",
                        BreedingMethod = rand.NextDouble() < 0.5 ? "群配" : "单配",
                        ExpectedLambingDate = d.AddDays(150 + rand.Next(-5, 6)),
                        IsSuccessful = rand.NextDouble() < 0.7,
                        FarmId = farmId
                    });
                }
                db.BreedingRecords.AddRange(list);
                await db.SaveChangesAsync(cancellationToken);
            }

            breedingIds = await db.BreedingRecords.AsNoTracking().Select(b => b.Id).ToListAsync(cancellationToken);

            // 3) PregnancyCheck
            var pcCount = await db.PregnancyChecks.AsNoTracking().CountAsync(cancellationToken);
            if (pcCount < 100 && breedingIds.Any())
            {
                var add = 100 - pcCount;
                var list = new List<PregnancyCheck>();
                for (int i = 0; i < add; i++)
                {
                    var bId = breedingIds[rand.Next(breedingIds.Count)];
                    var b = await db.BreedingRecords.AsNoTracking().FirstAsync(x => x.Id == bId, cancellationToken);
                    list.Add(new PregnancyCheck
                    {
                        BreedingId = b.Id,
                        CheckDate = b.BreedingDate.AddDays(35 + rand.Next(-3, 4)),
                        CheckMethod = "B超",
                        CheckResult = rand.NextDouble() < 0.85 ? "怀孕" : "未孕",
                        GestationWeek = 5,
                        Notes = null
                    });
                }
                db.PregnancyChecks.AddRange(list);
                await db.SaveChangesAsync(cancellationToken);
            }

            // 4) LambingRecord
            var lrCount = await db.LambingRecords.AsNoTracking().CountAsync(cancellationToken);
            if (lrCount < 100 && eweIds.Any())
            {
                var add = 100 - lrCount;
                var list = new List<LambingRecord>();
                for (int i = 0; i < add; i++)
                {
                    var date = DateTime.Today.AddDays(-rand.Next(0, 180));
                    list.Add(new LambingRecord
                    {
                        EweId = eweIds[rand.Next(eweIds.Count)],
                        LambingDate = date,
                        TotalLambs = 1,
                        LiveLambs = 1,
                        DeadLambs = 0,
                        LambingType = "顺产",
                        LambingStatus = "正常",
                        FarmId = farmId
                    });
                }
                db.LambingRecords.AddRange(list);
                await db.SaveChangesAsync(cancellationToken);
            }

            var lambingIds = await db.LambingRecords.AsNoTracking().Select(l => l.Id).ToListAsync(cancellationToken);

            // 5) 羔羊明细：补齐到至少100条（每个分娩取1只明细）
            var lambDetailCount = await db.LambDetails.AsNoTracking().CountAsync(cancellationToken);
            if (lambDetailCount < 100 && lambingIds.Any())
            {
                var need = 100 - lambDetailCount;
                var newDetails = new List<LambDetail>();
                for (int i = 0; i < need; i++)
                {
                    var lambingId = lambingIds[i % lambingIds.Count];
                    newDetails.Add(new LambDetail
                    {
                        LambingId = lambingId,
                        Gender = rand.NextDouble() < 0.5 ? "公" : "母",
                        BirthWeight = (decimal)(2.5 + rand.NextDouble() * 2.0),
                        HealthStatus = "健康"
                    });
                }
                db.LambDetails.AddRange(newDetails);
                await db.SaveChangesAsync(cancellationToken);
            }

            // 6) 生产记录：补齐到至少100条（生产相关字段）
            var prodRecordCount = await db.ProductionRecords.AsNoTracking().CountAsync(cancellationToken);
            if (prodRecordCount < 100)
            {
                var need = 100 - prodRecordCount;
                var types = new[] { "正常生产", "难产", "流产" };
                var newProdRecords = new List<ProductionRecord>();
                for (int i = 0; i < need; i++)
                {
                    newProdRecords.Add(new ProductionRecord
                    {
                        EweId = eweIds.Any() ? eweIds[rand.Next(eweIds.Count)] : 0,
                        ProductionDate = today.AddDays(-rand.Next(0, 365)),
                        ProductionType = types[rand.Next(types.Length)],
                        TotalOffspring = rand.Next(1, 3),
                        LiveOffspring = 1,
                        DeadOffspring = 0,
                        FarmId = farmId,
                        Notes = null
                    });
                }
                db.ProductionRecords.AddRange(newProdRecords);
                await db.SaveChangesAsync(cancellationToken);
            }

            // 7) 生产汇总：补齐到至少100条（使用 ProductionSummary 实体字段）
            var prodSummaryCount = await db.ProductionSummaries.AsNoTracking().CountAsync(cancellationToken);
            if (prodSummaryCount < 100)
            {
                var need = 100 - prodSummaryCount;
                var newSummaries = new List<ProductionSummary>();
                for (int i = 0; i < need; i++)
                {
                    var reportDate = new DateTime(today.Year, rand.Next(1, 13), rand.Next(1, 28));
                    newSummaries.Add(new ProductionSummary
                    {
                        ReportDate = reportDate,
                        FarmId = farmId,
                        Breed = breeds[rand.Next(breeds.Length)],
                        TotalEwes = rand.Next(80, 200),
                        BreedingEwes = rand.Next(40, 150),
                        PregnantEwes = rand.Next(30, 120),
                        LambingEwes = rand.Next(20, 100),
                        TotalLambs = rand.Next(10, 180),
                        LiveLambs = rand.Next(10, 170),
                        BreedingRate = (decimal)(rand.NextDouble()),
                        PregnancyRate = (decimal)(rand.NextDouble()),
                        LambingRate = (decimal)(rand.NextDouble()),
                        SurvivalRate = (decimal)(rand.NextDouble())
                    });
                }
                db.ProductionSummaries.AddRange(newSummaries);
                await db.SaveChangesAsync(cancellationToken);
            }

            // 8) 存栏历史：补齐到至少100条（使用 SheepInventoryHistory 实体字段）
            var invHistCount = await db.SheepInventoryHistories.AsNoTracking().CountAsync(cancellationToken);
            if (invHistCount < 100)
            {
                var need = 100 - invHistCount;
                var events = new[] { "入库", "出库", "转移", "死亡" };
                var invHist = new List<SheepInventoryHistory>();
                var allSheepIds = await db.Sheeps.AsNoTracking().Select(s => s.Id).ToListAsync(cancellationToken);
                for (int i = 0; i < need; i++)
                {
                    invHist.Add(new SheepInventoryHistory
                    {
                        SheepId = allSheepIds.Any() ? allSheepIds[rand.Next(allSheepIds.Count)] : 0,
                        ChangeDate = today.AddDays(-rand.Next(0, 365)),
                        ChangeType = events[rand.Next(events.Length)],
                        PreviousLocation = "A圈",
                        CurrentLocation = "B圈",
                        PreviousStatus = "存栏",
                        CurrentStatus = "存栏",
                        Reason = "测试数据",
                        OperatorId = null
                    });
                }
                db.SheepInventoryHistories.AddRange(invHist);
                await db.SaveChangesAsync(cancellationToken);
            }

            // 9) 存栏汇总：补齐到至少100条（使用 SheepInventorySummary 实体字段）
            var invSumCount = await db.SheepInventorySummaries.AsNoTracking().CountAsync(cancellationToken);
            if (invSumCount < 100)
            {
                var need = 100 - invSumCount;
                var invSum = new List<SheepInventorySummary>();
                for (int i = 0; i < need; i++)
                {
                    var reportDate = new DateTime(today.Year, rand.Next(1, 13), rand.Next(1, 28));
                    invSum.Add(new SheepInventorySummary
                    {
                        ReportDate = reportDate,
                        FarmId = farmId,
                        SheepType = rand.NextDouble() < 0.5 ? "种母" : "种公",
                        Breed = breeds[rand.Next(breeds.Length)],
                        Gender = rand.NextDouble() < 0.5 ? "公" : "母",
                        AgeGroup = rand.NextDouble() < 0.5 ? "成年" : "后备",
                        TotalCount = rand.Next(50, 200),
                        HealthyCount = rand.Next(40, 190),
                        SickCount = rand.Next(0, 10)
                    });
                }
                db.SheepInventorySummaries.AddRange(invSum);
                await db.SaveChangesAsync(cancellationToken);
            }
        }
    }
}
